<?php
namespace doumiaoduo\telecaptcha;

use common\models\datas\CardAttr;
use common\models\datas\CardSend;
use common\models\datas\Customer;
use common\models\datas\IsuserInfo;
use frontend\models\datas\Goods;
use frontend\models\datas\Mechanic;
use frontend\models\datas\Orders;
use frontend\models\datas\OrdersItems;
use yii\base\Action;
use yii\base\ActionEvent;
use yii\helpers\ArrayHelper;

class SendsmsmsgAction extends Action
{

    public $customer_name = '';

    public $customer_tele = '';

    public $saleman_name = '无';

    const EVENT_SEND_SMS_MESSAGE = 'sendsmsmessage';

    public $behaviorsData = [];

    public $good_name = '';
    /*
     * 点击获取验证码所进行的操作
     * 1. 获取手机号
     * 2. 生成随机验证码，以及短信内容
     * 3. 发送短信
     * 4. 成功之后保存短信码和事件至session中；失败返回错误信息
     */
    public function run($orderid = null)
    {
            //根据orderid得到机构的电话号码，如果一个订单多个商品不同机构的话，那么就得发送多条短信，不同内容商品，先不要费劲了，实现一个商品吧先
            $orderitem = OrdersItems::find()->where(['orders_id'=>$orderid])->one();//后期代码加非空等判断限制
            if(!empty($orderitem)){
                $mechanic_id = $orderitem->mechanic_id;
                if(!empty($mechanic_id)){
                    $mechanic = Mechanic::findOne($mechanic_id);
                    if(!empty($mechanic)){
                        $telenumber = $mechanic->telephone;
                        if(!preg_match("/1[34578]{1}\d{9}$/",$telenumber)){
                            \Yii::info("机构预留的联系方式非正常手机号：".$telenumber);
                            return;
                        }
                        $good_id = $orderitem->goods_id;
                        $good = Goods::findOne($good_id);
                        if(!empty($good)){
                            $this->good_name = $good->name;
                        }
                        $order = Orders::findOne($orderid);
                        $customer_id = $order->customer_id;
                        $customer = Customer::findOne($customer_id);
                        $cardattr = CardAttr::findOne(['customer_id'=>$customer_id]);
                        if(!empty($cardattr)){
                            if($cardattr->sendtype == 0){//实体卡
                                $saleman = IsuserInfo::findOne($cardattr->salesman_id);
                                if(!empty($saleman)){
                                    $this->saleman_name = $saleman->name;
                                }
                            }elseif($cardattr->sendtype == 2){//推荐卡
                                $customerman = Customer::findOne($cardattr->salesman_id);
                                if(!empty($customerman)){
                                    $this->saleman_name = $customerman->name;
                                }
                            }

                        }
                        $this->customer_name = $customer->name;
                        $this->customer_tele = $customer->mobile;
                    }else{
                        return ;
                    }

                }else{
                    return ;
                }

            }else{
                return ;
            }

            $maxcount_code = 5;

            if (empty($telenumber)) {
                $data['result'] = 'failed';
            } else {
                /*start: 每天每个手机号获取限制次数的验证码*/
                $telecode_info = \Yii::$app->cache->get('smscode_'.$telenumber);

                if ($telecode_info) {//缓存中已经存在此手机号的信息
                    $now = date('Y-m-d');
                    $codeinfo = unserialize($telecode_info);
                    $count = $codeinfo['count'] ? $codeinfo['count'] : 0;
                    $cachedate = $codeinfo['date'];
                    if ($now == $cachedate) {//当前的日期和缓存中该手机号的日期相同
                        if ($count >= $maxcount_code) {//是否超过每天限制的获取次数
                            $data['result'] = 'failed';
                            \Yii::error('此手机号于今天已经获取' . $maxcount_code . '次验证码，禁止再次获取');
                            return json_encode($data);
                        }
                    } else {//缓存中的日期不是今天，更新获取次数为0，日期为今天
                        $count = 0;
                        $codeinfo = array(
                            'count' => $count,
                            'date' => $now
                        );
                        $codeinfoser = serialize($codeinfo);
                        \Yii::$app->cache->set('smscode_'.$telenumber, $codeinfoser, 3600 * 24);
                    }
                } else {//缓存中不存在当前手机号的信息
                    /*
                     *保存次数和日期于缓存中
                     */
                    $codeinfo = array(
                        'count' => 0,
                        'date' => date('Y-m-d')
                    );
                    $codeinfoser = serialize($codeinfo);
                    \Yii::$app->cache->set('smscode_'.$telenumber, $codeinfoser, 3600 * 24);
                }
                /*end: 每天每个手机号获取限制次数的验证码*/
                //$content = "您的验证码是：【" . $code . "】。请不要把验证码泄露给其他人。";
                if (!\Yii::$app->session->isActive) {
                    \Yii::$app->session->open();
                }
                $cur_session = \Yii::$app->session;
                $cur_session->setTimeout(1800);//设置session的保存时间为5分钟，好像没有生效
                $cur_session->set('login_sms_time', time());
                $data['result'] = 'success';
                $res['telephone'] = $telenumber;
                $res['customer_name'] = $this->customer_name;
                $res['customer_tele'] = $this->customer_tele;
                $res['good_name'] = $this->good_name;
                $res['saleman_name'] = $this->saleman_name;
                $this->sendSmsmsg($res);//触发事件

                /*start: 更新缓存中的获取验证码的次数加1*/
                $phonecode = \Yii::$app->cache->get('smscode_'.$telenumber);
                $phonecode = unserialize($phonecode);
                $phonecode['count'] = $phonecode['count'] + 1;
                $phonecode = serialize($phonecode);
                \Yii::$app->cache->set('smscode_'.$telenumber, $phonecode, 3600 * 24);
                /*end: 更新缓存中获取验证码的次数*/
            }
            return json_encode($data);

    }

    //调用此方法触发发送短信的事件
    public function sendSmsmsg(array $res){
        $this->trigger(self::EVENT_SEND_SMS_MESSAGE, new ActionEvent(["data"=>$res]));
    }

    //重写行为
    public function behaviors()
    {
        return ArrayHelper::merge(parent::behaviors(), $this->behaviorsData);
    }


}